import { Component } from '@angular/core';
import { NavController, LoadingController, ToastController, Events } from 'ionic-angular';//AlertController
// import { Storage } from "@ionic/storage";
import { BaseUI } from '../../common/baseui';
import { ApiProvider } from '../../providers/api/api';
import { Clipboard } from '@ionic-native/clipboard';
// import { Device } from '@ionic-native/device';
// @IonicPage()
@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class ContactPage extends BaseUI{
  hours: any =  '';
  minutes: any = '';
  seconds: any = '';
  isHongbaoImg: boolean = true;
  isHongbao: boolean = false;
  isHongbaoText: boolean = false;
  isHongbaoGuang: boolean = false;
  hongbaoScore: any = 55;
  score: number = 0;
  window: boolean = false;//弹框是否显示
  isSign: boolean = false;//今日是否签到
  signNum: Number = 0;//连续签到天数
  mifenScore: any = 0;//用户米分
  qiandao: any[] = [5,6,7,8,9,10,''];
  marqueeStirng: string = 'MI555442323,抢到110米分. MI46546546,抢到22米分. MI231223,抢到32米分. MI45356232,抢到55米分. MI34324324,抢到80米分. MI555442323,抢到110米分. MI46546546,抢到22米分. MI231223,抢到32米分. MI45356232,抢到55米分. MI34324324,抢到80米分.';
  errorMessage: any;
  t: any = null;
  t2: any = null;
  duihuanYes: boolean = false;
  duihuanNo: boolean = false;
  constructor(public navCtrl: NavController,
              public api: ApiProvider,
              public loadingCtrl: LoadingController,
              public toastCtrl: ToastController,
              public events: Events,
              public clipboard: Clipboard
              // private alertCtrl: AlertController
              ) {
    super();
  }
  // 复制客服QQ
  copyQQ(){
    this.clipboard.copy("244690330@qq.com")
    this.duihuanYes = false;
    super.showToast(this.toastCtrl, "复制成功")
  }
  //米分兑换
  duihuan(){
    if(this.mifenScore < 1000){
      this.duihuanYes = false;
      this.duihuanNo = true;
    }else{
      this.duihuanYes = true;
      this.duihuanNo = false;
    }
  }
  // 抢红包
  qianghongClick(){
    let d = new Date();
    if((Number(d.getHours()) < 12) || (Number(d.getHours()) > 15 && Number(d.getHours()) < 19)){
      super.showToast(this.toastCtrl, '未到抢红包时间');
      return
    }
    if(Number(d.getHours()) >= 21){
      super.showToast(this.toastCtrl, '红包已抢光');
      return
    }
    this.api.userRedPacket({}).subscribe(res => {
      console.log('res', res)
      if(res['code'] === 500){
        super.showToast(this.toastCtrl, res['msg']);
        return
      }
      if(res['code'] === 2056){
        clearInterval(this.t);
        this.isHongbao = true;
        this.isHongbaoText = false;
        this.isHongbaoGuang = true;
        super.showToast(this.toastCtrl, res['msg']);
        return
      }
      this.hongbaoScore = res['result']
      this.isHongbaoImg = false
      this.getMifen();
    }, err => {
    })
  }
  comfirmSign(){
    this.window = false;
  }
  // 获取连续签到天数
  getUserSignInfo(){
    this.api.getUserSignInfo({}).subscribe(res => {
      console.log('res', res)
      if (res['result']){
        this.signNum = res['result']['continueSign']
        if(res['result']['todayIsSign']){
          this.isSign = true
        }else{
          this.isSign = false
        }
      }
    }, err => {
      if(err == 401 || err == 500){
        window.localStorage.removeItem('phoneNum')
        this.events.publish('toLogin');
      }
    })
  }
  // 签到
  signClick(i){
    if(this.isSign){
      super.showToast(this.toastCtrl, '您今日已签到过');
      return
    }
    if(i === this.signNum){
      let params = {
        miScore: this.qiandao[i]
      }
      if(i === 6){
        params['miScore'] = 22;
      }
      this.api.userSign(params).subscribe(res => {
        this.getUserSignInfo();
        this.getMifen();
        this.window = true;
        this.score = params['miScore'];
      }, err => {
        if(err == 401 || err == 500){
          window.localStorage.removeItem('phoneNum');
          this.events.publish('toLogin');
        }
      })
    }
  }
  // 红包页面埋点
  activeEvent(){
    let params = {
      'event': 'APP_RPV',
      'phoneNum': window.localStorage.getItem('phoneNum')
    }
    this.api.addEvent(params).subscribe(g => {
      console.log('红包页面埋点触发', g);
    }, err => {
      // if(err == 401 || err == 500){
      //   window.localStorage.removeItem('phoneNum')
      //   this.events.publish('toLogin');
      // }
    })
  }
  ionViewDidLoad(){
    this.activeEvent();
  }
  //下拉刷新
  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    setTimeout(() => {
      // this.getData();
      console.log('Async operation has ended');
      refresher.complete();
    }, 1000);
  }
  // 获取米分
  getMifen(){
    this.api.getAppUserInfo({phoneNum: window.localStorage.getItem('phoneNum')}).subscribe(f => {
      this.mifenScore = f['miScore']
    }, err => {
      this.errorMessage=<any>err;
    })
  }
  // 进入页面之前
  ionViewDidEnter(){
    this.getMifen()
    this.getUserSignInfo()
    this.getDaojishi()
  }
  // 离开页面之后
  ionViewDidLeave(){
    clearInterval(this.t);
    clearInterval(this.t2);
  }
  getDaojishi(){
    let d = new Date();
    if(Number(d.getHours()) < 12){
      this.isHongbao = false;
      this.isHongbaoText = false;
      this.isHongbaoGuang = false;
      clearInterval(this.t);
      clearInterval(this.t2);
      this.t = setInterval(() => {
        this.timeDown(12);
      },1000)
    } else if ((Number(d.getHours()) >= 12 && Number(d.getHours()) < 15) || (Number(d.getHours()) >= 19 && Number(d.getHours()) < 21) ){
      clearInterval(this.t);
      clearInterval(this.t2);
      this.isHongbao = true;
      this.isHongbaoText = true;
      this.isHongbaoGuang = false;
      this.t2 = setInterval(() => {
        let num = this.randomVal(10000000, 19999999)
        this.marqueeStirng = `MI${num},抢到110米分. MI${num+1000},抢到22米分. MI${num+1919},抢到32米分. MI${num+34543},抢到55米分. MI${num+546546},抢到80米分. MI${num+43543},抢到110米分. MI${num+324324},抢到22米分. MI${num+6567},抢到32米分. MI${num+657657},抢到55米分. MI${num+456456},抢到80米分.`
      }, 27 * 1000)
    }else if(Number(d.getHours()) >= 15 && Number(d.getHours()) < 19){
      this.isHongbao = false;
      this.isHongbaoText = false;
      this.isHongbaoGuang = false;
      clearInterval(this.t);
      clearInterval(this.t2);
      this.t = setInterval(() => {
        this.timeDown(19);
      },1000)
    }else{
      clearInterval(this.t);
      clearInterval(this.t2);
      this.isHongbao = true;
      this.isHongbaoText = false;
      this.isHongbaoGuang = true;
    }
  }
  randomVal(min,max){
    let random = Math.floor(Math.random()*(max-min+1)+min);
    return random;
  }
  // 时间倒计时插件
  timeDown(num) {
    //结束时间
    var d = new Date()
    d.setHours(num);
    d.setMinutes(0);
    d.setSeconds(0);
    //当前时间
    var nowDate = new Date();
    //相差的总秒数
    var totalSeconds = Number((d.getTime() - nowDate.getTime())/1000);
    //天数
    var days = Math.floor(totalSeconds / (60 * 60 * 24));
    console.log('days', days)
    //取模（余数）
    var modulo = totalSeconds % (60 * 60 * 24);
    //小时数
    var hours = Math.floor(modulo / (60 * 60));
    modulo = modulo % (60 * 60);
    //分钟
    var minutes = Math.floor(modulo / 60);
    //秒
    var seconds = Math.floor(modulo % 60);
    //输出到页面
    this.hours = hours;
    this.minutes = this.buling(minutes);
    this.seconds = this.buling(seconds);
  }
  // 补零
  buling (num) {
    return num < 10 ? '0' + num : num;
  }
}
